// request.js

class Request {
  constructor() {
    this.interceptors = {
      request: (config) => config,
      response: (res) => res,
      responseError: (err) => Promise.reject(err),
    };
  }

  setRequestInterceptor(fn) {
    this.interceptors.request = fn;
  }

  setResponseInterceptor(successFn, errorFn) {
    this.interceptors.response = successFn;
    if (errorFn) {
      this.interceptors.responseError = errorFn;
    }
  }

  request(options) {
    const config = this.interceptors.request({ ...options });

    return new Promise((resolve, reject) => {
      wx.request({
        ...config,
        success: (res) => {
          try {
            const result = this.interceptors.response(res);
            resolve(result);
          } catch (e) {
            reject(e);
          }
        },
        fail: (err) => {
          this.interceptors.responseError(err).catch(reject);
        },
      });
    });
  }

  get(url, data = {}, options = {}) {
    return this.request({ url, data, method: 'GET', ...options });
  }

  post(url, data = {}, options = {}) {
    return this.request({ url, data, method: 'POST', ...options });
  }

  put(url, data = {}, options = {}) {
    return this.request({ url, data, method: 'PUT', ...options });
  }

  delete(url, data = {}, options = {}) {
    return this.request({ url, data, method: 'DELETE', ...options });
  }
}

const request = new Request();

export default request;
